# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: jhkim

import datetime

import coin.exchange.bitmex.kr_rest.constants as bmconst


# bitmex expiration: 12:00 UTC
def expiry_accurate_datetime(expiry) -> datetime.datetime:
  assert isinstance(expiry, datetime.datetime)
  assert expiry.tzinfo is None
  expiry = expiry.replace(hour=12)
  return expiry


def find_quarter_contract_expiring_date_index(quarter_contract_date, current_datetime):
  for i, date in enumerate(quarter_contract_date):
    date = datetime.datetime.strptime(date, '%Y%m%d')
    date = expiry_accurate_datetime(date)
    if date >= current_datetime:
      return i
  raise RuntimeError("Please add more quarter dates")


def find_quarter_contract_expiring_date(current_datetime):
  idx = find_quarter_contract_expiring_date_index(bmconst.quarter_contract_date, current_datetime)
  return bmconst.quarter_contract_date[idx]


def find_next_quarter_contract_expiring_date(current_datetime):
  idx = find_quarter_contract_expiring_date_index(bmconst.quarter_contract_date, current_datetime)

  if idx + 1 < len(bmconst.quarter_contract_date):
    return bmconst.quarter_contract_date[idx + 1]
  raise RuntimeError("Please add more quarter dates")
